<?php

require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
            'cookie' => true
        ));

$session = $facebook->getSession();

if (!empty($session)) {
    # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
    try {
        $uid = $facebook->getUser();
        $user = $facebook->api('/me');
        
        #attempts to get college
      //   $fql = 'SELECT education FROM user WHERE uid = me()';
      // 	$ret_obj = $facebook->api(array(
      //                'method' => 'fql.query',
      //                'query' => $fql,
      //                ));
      // 	$schools = $ret_obj['data']['education'];
      // 	$colleges = array();
      // 	foreach ($schools as $s) {
      //   	 if ('College' == $s['type'])
      //       	$colleges[] = $s['school']['name'];
      // }
        
        #gets first_name,last_name,sex,email
       	//   $fql = 'SELECT first_name,last_name,sex,email FROM user WHERE uid = me()';
       	//  $ret_obj = $facebook->api(array(
       	//                'method' => 'fql.query',
       	//                'query' => $fql,
       	//                ));
       	//         foreach($ret_obj as $result)
       	// {
       	//   $first_name = $result['first_name'];
       	//   $last_name = $result['last_name'];
       	//   $email= $result['proxied_email'];
       	//    $sex= $result['sex'];
       	// 
       	// } 
	
	
        
    } catch (Exception $e) {   }

    if (!empty($user)) {
        #UNCOMMENT TO TEST DATA -  Tests to see the data retrieved from facebook, testing purposes only 

 	#echo "First Name? - $first_name   ";
 	#echo "Last Name? - $last_name   ";   
 	#echo "Email? - $email    ";  
 	#echo "Sex? - $sex"; 
 	#print_r($ret_obj);
   
	

        $username = $user['name'];
        $user = new User();
        $userdata = $user->checkUser($uid, 'facebook', $username);
        if(!empty($userdata)){
            session_start();
            $_SESSION['id'] = $userdata['id'];
			$_SESSION['oauth_id'] = $uid;
            $_SESSION['username'] = $userdata['username'];
            $_SESSION['oauth_provider'] = $userdata['oauth_provider'];
    		#COMMENT OUT TO TEST DATA the following line to stop the redirect to index.php when the facebook login is a success
    		header("location: index.php");
        }
    }
} else {
    # There's no active session, let's generate one
    $login_url = $facebook->getLoginUrl();
    header("Location: " . $login_url);
}
?>